package com.capybara.account.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.capybara.account.exception.MyErrorCodes;
import com.capybara.account.exception.MyServiceException;
import com.capybara.account.mapper.AuUserMapper;
import com.capybara.account.model.entity.AuUser;
import com.capybara.account.model.excel.AuUserExcel;
import com.capybara.account.model.query.AuUserQuery;
import com.capybara.account.service.IAuUserService;
import com.capybara.account.util.MyExcelUtil;
import com.github.yulichang.toolkit.JoinWrappers;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 用户 服务实现类
 *
 * @author wgc
 * @since 2024-09-12
 */
@Service
public class AuUserServiceImpl extends ServiceImpl<AuUserMapper, AuUser> implements IAuUserService {
    /**
     * 导出
     */
    @Override
    public void export(AuUserQuery param, HttpServletResponse response) {
        List<AuUserExcel> list = param.joinQuery(AuUser.class).list(AuUserExcel.class);
        MyExcelUtil.write(response, AuUserExcel.class, list, "用户");
    }

    /**
     * 保存用户
     *
     * @param param 参数
     * @return boolean
     */
    @Override
    public boolean save(AuUser param) {
        Long count = JoinWrappers.lambda(AuUser.class)
                .eq(AuUser::getUsername, param.getUsername())
                .count();
        if (count == 0) {
            return super.save(param);
        } else {
            throw new MyServiceException(MyErrorCodes.DUPLICATE_USERNAMES);
        }
    }


    /**
     * 按 ID 更新
     * 1、系统初始化用户不能修改
     *
     * @param param 参数
     * @return boolean
     */
    @Override
    public boolean updateById(AuUser param) {
        isSystemInit(Set.of(param.getId()));
        Long count = JoinWrappers.lambda(AuUser.class)
                .ne(AuUser::getId, param.getId())
                .eq(AuUser::getUsername, param.getUsername())
                .count();
        if (count == 0) {
            return super.updateById(param);
        } else {
            throw new MyServiceException(MyErrorCodes.DUPLICATE_USERNAMES);
        }
    }

    /**
     * 按 ID 移除
     *
     * @param ids 列表
     * @return boolean
     */
    @Override
    public boolean removeByIds(Collection<?> ids) {
        isSystemInit(ids);
        return super.removeByIds(ids);
    }


    /**
     * 检查是否包含系统用户
     *
     * @param ids IDS
     */
    private void isSystemInit(Collection<?> ids) {
        if (JoinWrappers.lambda(AuUser.class)
                .in(AuUser::getId, ids)
                .eq(AuUser::getIsSystemInit, true)
                .count() > 0) {
            throw new MyServiceException(MyErrorCodes.SYSTEM_INIT);
        }
    }
}
